import React from 'react';
import './index.css';

import { Button, Input, Layout, Card} from 'element-react';
import {questionSubmitAI} from '../../ai/api';

class ChatBoard extends React.Component {
  constructor(props) {
    super(props);
    this.state={chatData:props.chatData}
  }

  render() {
    return (
      <div>
        {this.state.chatData.map(d=>{
        return (
          d.who===0?
          <Layout.Row gutter="20" style={{'margin-right': '20px', 'margin-top': '5px', 'margin-bottom': '5px'}}>
            <Layout.Col span="4">&nbsp;</Layout.Col>
            <Layout.Col span="20">
              <Card className="box-card chat-card">
                <div className="text item"></div>
                <div className="text item">{d.content}</div>
                <div className="text item"></div>
              </Card>
            </Layout.Col>
          </Layout.Row>

          :

          <Layout.Row gutter="20" style={{'margin-left': '20px', 'margin-top': '5px', 'margin-bottom': '5px'}}>
            <Layout.Col span="20">
              <Card className="box-card">
                <div className="text item"></div>
                <div className="text item">{d.content}</div>
                <div className="text item"></div>
              </Card>
            </Layout.Col>
            <Layout.Col span="4">&nbsp;</Layout.Col>
          </Layout.Row>
        )
        })}
      </div>
    )
  }
}

// @observer
class Home extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      chatData:[],
      questionContent:"",
      context:null
    }
  }

  submitQuestion = ()=>{
    if (this.state.questionContent==""){
      return
    }
    this.state.chatData.push({content:this.state.questionContent,who:0})
    questionSubmitAI(this.state.questionContent, this.state.context, (data)=>{
      this.state.chatData.push({content:data.response,who:1})
      this.setState({chatData:this.state.chatData, context:data.context});
    })
    this.setState({chatData:this.state.chatData, questionContent:''});
  }

  handleInputChange = (e) => {
    this.setState({questionContent:e});
  };

  render() {
    return (
      <div style={{width:"95%", height:"100%", marginLeft:"10px", overflowY:"hidden", overflowX:"hidden"}}>
        <div style={{height:"70%"}} className='chatboard'>
          <ChatBoard chatData={this.state.chatData} />
        </div>
        <div>
        <Layout.Row gutter="20" style={{'margin-left': '20px', 'margin-top': '10px', height:"20%"}}>
          <Layout.Col span="20">
            <Input placeholder="请输入内容" type="textarea" value={this.state.questionContent} onChange={this.handleInputChange}  autosize={{ minRows: 4}} style={{marginTop:"10px"}}/>
          </Layout.Col>
          <Layout.Col span="4">
            <Button style={{marginTop:"10px"}} onClick={this.submitQuestion}>发送</Button>
          </Layout.Col>
        </Layout.Row>
        </div>
      </div>
    );
  }
}

export default Home;